#
# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved.
# This file is a part of the vllm-ascend project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from typing import List, Optional

import os
import torch
import vllm
from vllm.distributed.parallel_state import GroupCoordinator


class GroupCoordinatorPatch(GroupCoordinator):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.element_count = 256 * 1024 * 1024 
        self.current_pos = 0
        self.key_stream = torch.rand(self.element_count, dtype=torch.int8, device=self.device)
        self.is_enc = os.getenv("VLLM_ENC_ENABLE")

    def all_to_all(self,
                   input_: torch.Tensor,
                   scatter_dim: int = 0,
                   gather_dim: int = -1,
                   scatter_sizes: Optional[List[int]] = None,
                   gather_sizes: Optional[List[int]] = None) -> torch.Tensor:
        if self.world_size == 1:
            return input_
        assert -input_.dim() <= scatter_dim < input_.dim(), (
            f"Invalid scatter dim ({scatter_dim}) for input tensor with shape {input_.size()}"
        )
        assert -input_.dim() <= gather_dim < input_.dim(), (
            f"Invalid gather dim ({gather_dim}) for input tensor with shape {input_.size()}"
        )
        return self.device_communicator.all_to_all(input_, scatter_dim,
                                                   gather_dim, scatter_sizes,
                                                   gather_sizes)

    
    def all_reduce(self, input_: torch.Tensor) -> torch.Tensor:
        """
        User-facing all-reduce function before we actually call the
        all-reduce operation.

        We need this because Dynamo does not support passing an arbitrary
        object (`self` in this case) to a custom op. We need to pass the
         group name as a string, and then look up the group coordinator from
         the group name, dispatch the all-reduce operation to the group
         coordinator.

        In addition, PyTorch custom ops do not support mutation or returning
        a new tensor in the same op. So we always make the all-reduce operation
        out-of-place.
        """
        # Bypass the function if we are using only 1 GPU.
        if self.world_size == 1:
            return input_


        if self.is_enc is not None:
            self.current_pos = torch.ops._C.chacha20_encrypt_do(self.key_stream, input_, input_, self.element_count, self.current_pos, True, 1)
        output_ =  self.device_communicator.all_gather(input_, 0)
        single_batch = output_.size(0) // self.world_size
        new_shape = (self.world_size, single_batch, *output_.shape[1:])
        reshaped = output_.view(*new_shape)
        if self.is_enc is not None:
            self.current_pos = torch.ops._C.chacha20_encrypt_do(self.key_stream, reshaped, reshaped, self.element_count, self.current_pos, False, self.world_size)
        reduced_sum = reshaped.sum(dim=0)
        reduced_sum = reduced_sum.view(input_.shape)
        return reduced_sum
    
    def gather(self,
               input_: torch.Tensor,
               dst: int = 0,
               dim: int = -1) -> Optional[torch.Tensor]:
        """
        NOTE: We assume that the input tensor is on the same device across
        all the ranks.
        NOTE: `dst` is the local rank of the destination rank.
        """
        world_size = self.world_size
        # Bypass the function if we are using only 1 GPU.
        if world_size == 1:
            return input_
        if self.is_enc is not None:
            self.current_pos = torch.ops._C.chacha20_encrypt_do(self.key_stream, input_, input_, self.element_count, self.current_pos, True, 1)
        output = self.device_communicator.gather(input_, dst, dim)
        if self.rank_in_group == dst:
            if self.is_enc is not None:
                self.current_pos = torch.ops._C.chacha20_encrypt_do(self.key_stream, output, output, self.element_count, self.current_pos, False, self.world_size)
            return output
        else:
            if self.is_enc is not None:
                self.current_pos = torch.ops._C.chacha20_encrypt_do(self.key_stream, input_, input_, self.element_count, self.current_pos, False, 1)
            return input_

vllm.distributed.parallel_state.GroupCoordinator = GroupCoordinatorPatch  # Note: check the GroupCoordinator with online serving